package Socket;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class ClientUI extends JFrame {
    private JTextArea chatTextArea;
    private JTextField inputTextField;
    private JButton sendButton;
    private Socket socket;
    private PrintWriter out;
    private BufferedReader in;

    public ClientUI() throws IOException {
        setTitle("Chat Client");
        setSize(400, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // 创建组件
        chatTextArea = new JTextArea();
        chatTextArea.setEditable(false); // 文本域不可编辑
        JScrollPane scrollPane = new JScrollPane(chatTextArea);

        inputTextField = new JTextField(20);
        sendButton = new JButton("发送");

        // 添加按钮监听器
        sendButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String message = inputTextField.getText().trim();
                if (!message.isEmpty()) {
                    chatTextArea.append("You: " + message + "\n");
                    inputTextField.setText(""); // 清空输入框
                    out.println(message); // 发送消息到服务器
                }
            }
        });

        // 布局管理器
        JPanel bottomPanel = new JPanel();
        bottomPanel.add(inputTextField);
        bottomPanel.add(sendButton);

        setLayout(new BorderLayout());
        add(scrollPane, BorderLayout.CENTER);
        add(bottomPanel, BorderLayout.SOUTH);

        // 连接到服务器
        connectToServer();

        setVisible(true);
    }

    private void connectToServer() throws IOException {
        socket = new Socket("176.201.104.11", 8088);
        out = new PrintWriter(socket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        // 启动接收线程
        Thread receiveThread = new Thread(new Runnable() {
            @Override
            public void run() {
                String receivedMessage;
                try {
                    while ((receivedMessage = in.readLine()) != null) {
                        chatTextArea.append(receivedMessage + "\n");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        receiveThread.start();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            try {
                new ClientUI();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }
}
